package xxl.robotlegs.extensions.contextsignal.impl 
{
	import xxl.robotlegs.extensions.contextsignal.api.IContextSignal;
	/**
	 * ...
	 * @author XXL
	 */
	public class ContextSignalRelay 
	{
		private var _source:IContextSignal;
		private var _destination:IContextSignal;
		private var _types:Array;
		private var _active:Boolean = false;
		
		public function ContextSignalRelay(source:IContextSignal, destination:IContextSignal, types:Array = null) 
		{
			_source = source;
			_destination = destination;
			_types = types || [];
		}
		
		public function start():ContextSignalRelay
		{
			if (!_active)
			{
				_active = true;
				addListeners();
			}
			return this;
		}
		
		public function stop():ContextSignalRelay
		{
			if (_active)
			{
				_active = false;
				removeListeners();
			}
			return this;
		}
		
		public function addKey(mapKey:Object):void
		{
			_types.push(mapKey);
			_active && addListener(mapKey);
		}
		
		public function removeKey(mapKey:Object):void
		{
			const index:int = _types.indexOf(mapKey);
			if (index > -1)
			{
				_types.splice(index, 1);
				removeListener(mapKey);
			}
		}
		
		public function hasKey(mapKey:Object):Boolean
		{
			const index:int = _types.indexOf(mapKey);
			if (index >= 0)
			{
				return true;
			}
			return false;
		}
		
		//----------private
		
		private function removeListener(key:Object):void
		{
			_source.removeFromMap(key, _destination.dispatch);
		}
		
		private function addListener(key:Object):void
		{
			_source.addToMap(key, _destination.dispatch).safelyExecute = false;//safelyExecute不支持...args方法
		}
		
		private function addListeners():void
		{
			for each(var key:Object in _types)
			{
				addListener(key);
			}
		}
		
		private function removeListeners():void
		{
			for each(var key:Object in _types)
			{
				removeListener(key);
			}
		}
	}

}